<template>
  <el-card>
    <h2>基础配置门店提交</h2>
    <h3>待提交门店</h3>
     <el-table :data="pendingList" style="width: 100%">
      <el-table-column prop="storeName" label="门店名称" />
      <el-table-column prop="franchisee" label="加盟商" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="province" label="省份" />
      <el-table-column prop="address" label="地址" />
      <el-table-column label="加盟日期">
        <template #default="{ row }">
          {{ row.joinDate ? row.joinDate.split('T')[0] : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="warning" size="small" @click="onEdit(row.storeId)">编辑</el-button>
          <el-button type="danger" size="small" @click="onReject(row.storeId)">驳回</el-button>
          <el-button size="small" @click="viewTakeoutDetail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <h3 style="margin-top:32px;">已提交门店</h3>
    <el-table :data="reviewedList" style="width: 100%">
      <el-table-column prop="store.storeName" label="门店名称" />
      <el-table-column label="员工1（提交人）">
        <template #default="{ row }">
          {{ getEmployee1Name(row.store.employee1Id) }}
        </template>
      </el-table-column>
      <el-table-column label="下一位操作者">
        <template #default="{ row }">
          {{ getEmployee2Name(row.store.employee2Id) }}
        </template>
      </el-table-column>
      <el-table-column label="操作时间">
        <template #default="{ row }">
          {{ getOperationTime(row) }}
        </template>
      </el-table-column>
      <el-table-column label="阶段">
        <template #default="{ row }">
          {{ getStageText(row.store.status) }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default>已提交</template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="small" @click="viewPhotos(row.store.storeId)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="reviewedPageNum"
      :page-size="reviewedPageSize"
      :total="reviewedTotal"
      @current-change="handleReviewedPageChange"
      layout="total, prev, pager, next"
      style="margin-top: 16px;"
    />
    <el-dialog v-model="dialogVisible" title="提交图片详情" width="600px">
      <div v-if="photos">
        <div v-for="(url, key) in photoMap" :key="key" style="margin-bottom:12px;">
          <b>{{ key }}：</b>
          <img v-if="photos[url]" :src="photos[url]" style="max-width:400px;max-height:200px;" />
          <span v-else>无</span>
        </div>
      </div>
      <div v-else>加载中...</div>
    </el-dialog>
    <el-dialog v-model="showNextOperatorDialog" title="请输入下一位操作者名字" width="400px">
      <el-input v-model="nextOperatorName" placeholder="请输入名字" />
      <template #footer>
        <el-button @click="handleNextOperatorCancel">取消</el-button>
        <el-button type="primary" @click="handleNextOperatorSubmit">提交</el-button>
      </template>
    </el-dialog>
    
    <!-- 外卖详情弹窗 -->
    <el-dialog v-model="takeoutDetailDialogVisible" title="外卖详情" width="600px">
      <div v-if="takeoutDetailData">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="门店ID">{{ takeoutDetailData.storeId }}</el-descriptions-item>
          <el-descriptions-item label="门店名称">{{ takeoutDetailData.storeName }}</el-descriptions-item>
          <el-descriptions-item label="加盟商">{{ takeoutDetailData.franchisee }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{ takeoutDetailData.phone }}</el-descriptions-item>
          <el-descriptions-item label="省份">{{ takeoutDetailData.province }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ takeoutDetailData.address }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ takeoutDetailData.status }}</el-descriptions-item>
        </el-descriptions>
        <h4 style="margin-top: 20px;">外卖照片</h4>
        <div v-for="type in [0,2,3]" :key="type" style="margin-bottom: 12px;">
          <b>{{ takeoutPhotoTypeLabels[type] }}：</b>
          <template v-if="takeoutPhotoGroups[type] && takeoutPhotoGroups[type].length">
            <div v-for="photo in takeoutPhotoGroups[type]" :key="photo.photoId" style="margin-bottom: 8px;">
              <img :src="photo.photoPath" style="max-width: 200px; max-height: 120px; margin-right: 8px;" />
              <div style="margin-top: 4px; font-size: 12px; color: #666;">
                <span>平台ID: {{ photo.platformId || '-' }}</span>
                <span style="margin-left: 12px;">账号: {{ photo.platformAccount || '-' }}</span>
                <span style="margin-left: 12px;">密码: {{ photo.platformPassword || '-' }}</span>
              </div>
            </div>
          </template>
          <template v-else>
            <span>无</span>
          </template>
        </div>
      </div>
      <div v-else>暂无数据</div>
      <template #footer>
        <el-button @click="takeoutDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '@/store/user';
import { formatDateTime } from '../utils/dateUtils';

const pendingList = ref([]);
const reviewedList = ref([]);
const router = useRouter();
const dialogVisible = ref(false);
const photos = ref(null);
const photoMap = {
  '菜单图片': 'menuImage',
  '装修图片': 'decorationImage',
  '活动图片': 'activityImage',
  '基础配置图片': 'configImage',
};

// 已提交门店分页相关
const reviewedPageNum = ref(1);
const reviewedPageSize = ref(10);
const reviewedTotal = ref(0);

const userStore = useUserStore();

const showNextOperatorDialog = ref(false);
const nextOperatorName = ref('');
const currentStoreId = ref(null);
const employee1List = ref([]);

// 外卖详情相关
const takeoutDetailDialogVisible = ref(false);
const takeoutDetailData = ref(null);
const takeoutPhotoGroups = ref({});
const takeoutPhotoTypeLabels = {
  0: '京东外卖',
  2: '美团外卖',
  3: '饿了么外卖'
};

function getEmployee1Name(id) {
  const emp = employee1List.value.find(e => e.employeeId === id);
  return emp ? emp.name : id || '-';
}

async function fetchList() {
  try {
    // status=1 待审核 - 根据员工角色使用不同接口
    let url1;
    if (Number(userStore.roleCode) === 3) {
      // 管理员：使用原有接口
      url1 = 'http://121.43.176.9:8090/api/store/status1';
    } else if (Number(userStore.roleCode) === 1) {
      // 员工1：使用新接口，获取分配给该员工1的门店
      url1 = `http://121.43.176.9:8090/api/store/status1-by-employee1?employee1Id=${userStore.userId}`;
    } else {
      // 其他员工：使用原有接口
      url1 = 'http://121.43.176.9:8090/api/store/status1';
      if (Number(userStore.roleCode) !== 3) {
        url1 += `?createUserId=${userStore.userId}`;
      }
    }
    
    const res1 = await fetch(url1).then(r => r.json());
    if (res1.code === 200) {
      if (Array.isArray(res1.data)) {
        pendingList.value = res1.data;
      } else if (Array.isArray(res1.data?.records)) {
        pendingList.value = res1.data.records;
      } else {
        pendingList.value = [];
      }
    } else {
      pendingList.value = [];
      ElMessage.error(res1.msg || '加载失败');
    }
    
    // status=2、3、4、5 已审核 - 根据员工角色使用不同接口
    let url2to5;
    if (Number(userStore.roleCode) === 3) {
      // 管理员：使用原有接口
      url2to5 = 'http://121.43.176.9:8090/api/store/status2to5';
    } else if (Number(userStore.roleCode) === 1) {
      // 员工1：使用新接口，获取分配给该员工1的门店
      url2to5 = `http://121.43.176.9:8090/api/store/status2to5-by-employee1?employee1Id=${userStore.userId}`;
    } else {
      // 其他员工：使用原有接口
      url2to5 = 'http://121.43.176.9:8090/api/store/status2to5';
    }
    
    const res2 = await fetch(url2to5).then(r => r.json());
    if (res2.code === 200) {
      let allData = [];
      
      // 处理不同的数据格式
      if (res2.data) {
        if (Array.isArray(res2.data)) {
          allData = res2.data;
        } else if (res2.data.records && Array.isArray(res2.data.records)) {
          allData = res2.data.records;
        } else if (res2.data.list && Array.isArray(res2.data.list)) {
          allData = res2.data.list;
        }
      }
      
      // console.log('API响应数据:', res2.data);
      // console.log('已审核门店总数:', allData.length);
      // console.log('当前页码:', reviewedPageNum.value);
      // console.log('每页大小:', reviewedPageSize.value);
      
      // 按操作时间排序，时间越靠后的排在越前面
      allData.sort((a, b) => {
        const timeA = getOperationTimeValue(a);
        const timeB = getOperationTimeValue(b);
        return timeB - timeA; // 降序排列，最新的在前
      });
      
      // 前端分页处理
      reviewedTotal.value = allData.length;
      const startIndex = (reviewedPageNum.value - 1) * reviewedPageSize.value;
      const endIndex = startIndex + reviewedPageSize.value;
      
      // console.log('分页索引:', startIndex, '到', endIndex);
      
      // 确保索引在有效范围内
      const validStartIndex = Math.max(0, startIndex);
      const validEndIndex = Math.min(allData.length, endIndex);
      
      reviewedList.value = allData.slice(validStartIndex, validEndIndex);
      
      // console.log('当前页显示数据:', reviewedList.value.length);
      // console.log('分页组件总数:', reviewedTotal.value);
    } else {
      reviewedList.value = [];
      reviewedTotal.value = 0;
      ElMessage.error(res2.msg || '加载失败');
    }
  } catch (e) {
    pendingList.value = [];
    reviewedList.value = [];
    reviewedTotal.value = 0;
    ElMessage.error('加载失败');
  }
}

function handleReviewedPageChange(val) {
  reviewedPageNum.value = val;
  fetchList();
}

async function fetchEmployee1List() {
  const res = await fetch('http://121.43.176.9:8090/api/employee/type1/list').then(r => r.json());
  if (res.code === 200) {
    employee1List.value = res.data;
  } else {
    employee1List.value = [];
  }
}

const employee2List = ref([]);
function getEmployee2Name(id) {
  const emp = employee2List.value.find(e => e.employeeId === id);
  return emp ? emp.name : id || '-';
}

function getStageText(status) {
  switch (status) {
    case 2: return '阶段2';
    case 3: return '阶段3';
    case 4: return '阶段4';
    case 5: return '阶段5';
    default: return '-';
  }
}

function getOperationTime(row) {
  // 优先显示员工1提交图片的时间
  if (row.employeeType1PhotosCreateTime) {
    return formatDateTime(row.employeeType1PhotosCreateTime);
  }
  
  // 如果没有员工1提交时间，显示用户认证时间
  if (row.userCertificationCreateTime) {
    return formatDateTime(row.userCertificationCreateTime);
  }
  
  // 如果都没有，显示流程日志时间
  if (row.submissionLogTime) {
    return formatDateTime(row.submissionLogTime);
  }
  
  // 最后兜底显示门店创建时间
  if (row.store?.createTime) {
    return formatDateTime(row.store.createTime);
  }
  
  return '-';
}

function getOperationTimeValue(row) {
  // 优先使用员工1提交图片的时间
  if (row.employeeType1PhotosCreateTime) {
    return new Date(row.employeeType1PhotosCreateTime).getTime();
  }
  
  // 如果没有员工1提交时间，使用用户认证时间
  if (row.userCertificationCreateTime) {
    return new Date(row.userCertificationCreateTime).getTime();
  }
  
  // 如果都没有，使用流程日志时间
  if (row.submissionLogTime) {
    return new Date(row.submissionLogTime).getTime();
  }
  
  // 最后兜底使用门店创建时间
  if (row.store?.createTime) {
    return new Date(row.store.createTime).getTime();
  }
  
  // 如果都没有时间信息，返回0（排在最后）
  return 0;
}
async function fetchEmployee2List() {
  const res = await fetch('http://121.43.176.9:8090/api/employee/type2/list').then(r => r.json());
  if (res.code === 200) {
    employee2List.value = res.data;
  } else {
    employee2List.value = [];
  }
}

function goDetail(storeId) {
  router.push({ name: 'EmployeeType1Detail', params: { storeId } });
}

function onEdit(storeId) {
  router.push({ name: 'EmployeeType1Detail', params: { storeId }, query: { edit: 1 } });
}

async function handleNextOperatorSubmit() {
  if (!nextOperatorName.value) {
    ElMessage.warning('请输入下一位操作者名字');
    return;
  }
  const params = new URLSearchParams();
  params.append('storeId', currentStoreId.value);
  params.append('employeeName', nextOperatorName.value);
  params.append('employeeId', userStore.userId);
  const url = `http://121.43.176.9:8090/api/store/employeeToNext?${params.toString()}`;
  try {
    const res = await fetch(url, {
      method: 'GET',
    }).then(r => r.json());
    if (res.code === 200) {
      ElMessage.success('提交成功');
      showNextOperatorDialog.value = false;
      nextOperatorName.value = '';
      currentStoreId.value = null;
      await fetchList();
    } else {
      ElMessage.error(res.msg || '提交失败');
    }
  } catch (e) {
    ElMessage.error('提交失败');
  }
}

function handleNextOperatorCancel() {
  showNextOperatorDialog.value = false;
  nextOperatorName.value = '';
  currentStoreId.value = null;
}

async function viewPhotos(storeId) {
  dialogVisible.value = true;
  photos.value = null;
  // 获取员工1上传的图片
  const url = `http://121.43.176.9:8090/api/employee/type1/photos?storeId=${storeId}`;
  console.log('访问的完整URL:', url);
  const res = await fetch(url).then(r => r.json());
  if (res.code === 200 && res.data) {
    photos.value = res.data;
  } else {
    photos.value = {};
    ElMessage.error(res.msg || '未找到图片');
  }
}

async function onReject(storeId) {
  ElMessageBox.confirm('确定要驳回该门店吗？', '提示', { type: 'warning' })
    .then(async () => {
      // 调用后端接口，将门店状态改为6
      const res = await fetch(`http://121.43.176.9:8090/api/store/update-status6`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `storeId=${storeId}`
      }).then(r => r.json());
      if (res.code === 200) {
        ElMessage.success('已驳回，门店状态已更新为6');
        fetchList();
      } else {
        ElMessage.error(res.msg || '驳回失败');
      }
    });
}

async function viewTakeoutDetail(row) {
  takeoutDetailData.value = row;
  takeoutDetailDialogVisible.value = true;
  // 获取外卖照片
  takeoutPhotoGroups.value = {};
  const res = await fetch(`http://121.43.176.9:8090/api/store-setup-photos/by-store/${row.storeId}`).then(r => r.json());
  if (res.code === 200 && Array.isArray(res.data)) {
    // 按类型分组，存储完整的照片对象，只显示外卖相关类型
    res.data.forEach(photo => {
      if ([0, 2, 3].includes(photo.photoType)) { // 只显示外卖相关类型
        if (!takeoutPhotoGroups.value[photo.photoType]) {
          takeoutPhotoGroups.value[photo.photoType] = [];
        }
        takeoutPhotoGroups.value[photo.photoType].push(photo);
      }
    });
  }
}

onMounted(() => {
  fetchList();
  fetchEmployee1List();
  fetchEmployee2List();
});
</script> 